from django.http import HttpResponse
from django.shortcuts import redirect, render, reverse
from django import forms
from io import BytesIO

from forum import models
from forum.models import ForumUser, Post, Like, Comment, Reply
from forum.utils.captcha import check_code


# def show_index(request):
#     """主页"""
#     return render(request, "index.html")

########################################################################################################################
# 管理员

def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    user_name = request.POST.get("user")
    passwd = request.POST.get("pwd")
    try:
        user = ForumUser.objects.get(username=user_name)
    except:
        return render(request, 'login.html', {'err_msg': "用户不存在"})
    if user.is_admin == 1 and user.password == passwd:
        request.session["admin"] = 'true'
        return redirect("/admin/")
    return render(request, "login.html", {"err_msg": "密码错误"})


def admin(request):
    if request.session.get("admin") != 'true':
        return redirect("/admin/login")
    posts_data = Post.objects.all()
    users = ForumUser.objects.all()
    return render(request, 'admin_post.html', {"posts": posts_data, "users": users})


def del_post(request):
    if request.session.get("admin") != "true":
        return redirect("admin/login")
    try:
        post = Post.objects.get(id=request.GET.get("id"))
    except:
        return HttpResponse("{'success': 'false', 'message': 'NotFound'}")
    post.delete()
    return redirect("/admin")


def user_add(request):
    if request.session.get("admin") != 'true':
        return redirect("/admin/login")
    if request.method == "GET":
        return render(request, 'admin_users_add.html')
    isadmin = 0
    sexid = 2
    username = request.POST.get("username")
    for u in ForumUser.objects.all():
        if u.username == username:
            return render(request, 'admin_users_add.html', {'msg': "用户已存在"})
    email = request.POST.get("email")
    password = request.POST.get("password")
    age = request.POST.get("age")
    sex = request.POST.get("sex")
    if sex == "男":
        sexid = 1
    if request.POST.get("is_staff") == 'on':
        isadmin = 1
    user = ForumUser(username=username, email=email, password=password, age=age, sex=sexid, is_admin=isadmin)
    user.save()
    return render(request, 'admin_users_add.html', {'msg': "创建成功"})


def logout(request):
    request.session.clear()
    return redirect("/admin/login/")


def user_control(request):
    if request.session.get("admin") != "true":
        return redirect("/admin/login")
    if request.GET.get("cmd") == "del":
        ForumUser.objects.get(id=request.GET.get("id")).delete()
        return redirect("/admin/user_control/")
    if request.GET.get("cmd") == "addadmin":
        user = ForumUser.objects.get(id=request.GET.get("id"))
        user.is_admin = 1
        user.save()
    if request.GET.get("cmd") == "removeadmin":
        user = ForumUser.objects.get(id=request.GET.get("id"))
        user.is_admin = 0
        user.save()
    return render(request, "user_control.html", {"users": ForumUser.objects.all()})


########################################################################################################################


def show_index(request):
    """主页"""
    posts = models.Post.objects.all()
    likes = models.Like.objects.all()
    comments = models.Comment.objects.all()
    return render(request, "index.html", {"posts": posts, "likes": likes, "comments": comments})


class UserRegisterForm(forms.ModelForm):
    """注册表单"""

    # 重新字段，改变验证规则（字段长度、正则表达式）
    class Meta:
        model = models.ForumUser
        # 没有写重复密码###########################################################################################
        fields = ["username", "password", "email", "sex", "age"]
        widgets = {
            "password": forms.PasswordInput(),
            "email": forms.EmailInput(),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def show_register(request):
    """注册验证"""
    if request.method == "POST":
        # 提交表单，POST方式
        form = UserRegisterForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect("user_login.html")  # 登录页面的URL名称
    else:
        # GET请求，返回注册页面
        form = UserRegisterForm()

    return render(request, "register.html", {"form": form})


class UserLoginForm(forms.Form):
    """登录表单"""

    username = forms.CharField(
        label="用户名",
        required=True,
    )

    password = forms.CharField(
        label="密码",
        required=True,
        widget=forms.PasswordInput(render_value=True),
    )

    image_code = forms.CharField(
        label="验证码",
        required=True,
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def show_login(request):
    """登录验证"""
    # post提交，登录验证
    if request.method == "POST":
        form = UserLoginForm(data=request.POST)
        # 检查通过表单提交的数据是否有效，有效创建clean_date字典（保存表单数据）
        if form.is_valid():
            # 将用户输入验证码从clean_data中去除（因为数据库中没有验证码），同时得到用户输入验证码
            user_input_code = form.cleaned_data.pop("image_code")
            true_code = request.session.get("image_code_session", "")

            if true_code.upper() != user_input_code.upper():
                form.add_error("image_code", "验证码错误！")
                return render(request, "user_login.html", {"form": form})

            # 判断数据库是否有该数据
            user_judge = models.ForumUser.objects.filter(**form.cleaned_data).first()
            if user_judge:
                # 账号密码正确，创建session
                request.session["info"] = {
                    "id": user_judge.id,
                    "username": user_judge.username,
                }
                request.session.set_expiry(60 * 60 * 24)
                return redirect("/")  # 重定向到主页或其他页面
            else:
                form.add_error("password", "用户名或密码错误！")
                return render(request, "user_login.html", {"form": form})

    # get，访问页面
    if request.method == "GET":
        form = UserLoginForm()
    return render(request, "user_login.html", {"form": form})


def show_userInfo(request, userID):
    """
    显示用户信息
    """
    try:
        # 假设你知道的主键是1，你可以替换成实际的主键值
        row_data = ForumUser.objects.get(pk=userID)
        # 现在，row_data 将包含相应主键的模型实例
    except ForumUser.DoesNotExist:
        # 处理找不到数据的情况
        return HttpResponse("用户数据异常，请联系管理员！")
    return render(request, "userInfo.html", {"user": row_data})


def show_edit(request, userID):
    """用户信息编辑"""
    # 获取对应用户数据（封装成对象）
    user_one = models.ForumUser.objects.filter(id=userID).first()
    if request.method == "GET":
        # 将数据自动填充到表单
        form = UserRegisterForm(instance=user_one)
    if request.method == "POST":
        # 修改对应用户的数据
        form = UserRegisterForm(data=request.POST, instance=user_one)
        if form.is_valid():
            form.save()
            # 进行重定向
            return redirect('/' + str(userID) + '/')
    return render(request, "edit.html", {"form": form})


def image_code(request):
    """生成图片验证码"""
    # 调用函数生成图片余字符串
    img, code_string = check_code()
    # 字符串保存session
    request.session["image_code_session"] = code_string
    # 验证码时间为60秒
    request.session.set_expiry(60)
    # 图片保存到内存
    stream = BytesIO()
    img.save(stream, "png")
    return HttpResponse(stream.getvalue())


def show_logout(request):
    """用户注销"""
    request.session.clear()
    return redirect("/")


def post_list(request):
    """
    全部帖子
    """
    posts = models.Post.objects.all()
    return render(request, "post_list.html", {"posts": posts})


class PostForm(forms.ModelForm):
    """
    帖子表单
    """

    class Meta:
        model = models.Post
        fields = ['title', 'content']
        widgets = {
            "content": forms.TextInput,
        }

    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)
    # for name, field in self.fields.items():
    #     if name == "content":
    #         field.widget.attrs = {"placeholder": field.label}
    #     else:
    #         field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def post_create(request):
    """ 添加帖子 """
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            if request.session.get('info'):
                post.user_id = request.session.get('info').get('id')
                post.save()
                return redirect('home')
            else:
                # 如果用户未登录或不是 ForumUser 实例，处理这种情况
                return HttpResponse("用户未登录或不是有效的用户实例")
    else:
        form = PostForm()
    return render(request, 'post_edit.html', {'form': form})


def add_like(request, userID, postID):
    """
    添加点赞
    """
    # 找该用户所有的like
    likes = Like.objects.filter(user_id=userID)
    for like in likes:
        if like.post.id == postID:
            like.delete()
            return redirect('home')
    # 如果没有，新建一个
    oneLike = Like()
    oneLike.user = ForumUser.objects.filter(id=userID).first()
    oneLike.post = Post.objects.filter(id=postID).first()
    oneLike.save()
    return redirect('home')


class CommentForm(forms.ModelForm):
    """
    评论表单
    """

    class Meta:
        model = models.Comment
        fields = ['content']
        widgets = {
            "content": forms.TextInput,
        }


def add_comment(request, userID, postID):
    """
    添加评论
    """
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            if request.session.get('info'):
                comment.user_id = userID
                comment.post_id = postID
                comment.save()
                return redirect('home')
            else:
                # 如果用户未登录或不是 ForumUser 实例，处理这种情况
                return HttpResponse("用户未登录或不是有效的用户实例")
    else:
        form = CommentForm()
    return render(request, 'add_comment.html', {'form': form})


class ReplyForm(forms.ModelForm):
    """
    回复表单
    """

    class Meta:
        model = models.Reply
        fields = ['content']
        widgets = {
            "content": forms.TextInput,
        }


def add_reply(request, userID, commentID):
    """
    添加评论
    """
    if request.method == 'POST':
        form = ReplyForm(request.POST)
        if form.is_valid():
            reply = form.save(commit=False)
            if request.session.get('info'):
                reply.user_id = userID
                reply.comment_id = commentID
                reply.save()
                return redirect('home')
            else:
                # 如果用户未登录或不是 ForumUser 实例，处理这种情况
                return HttpResponse("用户未登录或不是有效的用户实例")
    else:
        form = ReplyForm()
    return render(request, 'add_reply.html', {'form': form})


def show_post_one(request, postID):
    """
    显示一条帖子
    """
    try:
        post = models.Post.objects.get(id=postID)
        comments = models.Comment.objects.filter(post_id=postID)
        return render(request, 'show_post_one.html', {"post": post, "comments": comments})
    except ForumUser.DoesNotExist:
        # 处理找不到数据的情况
        return HttpResponse("用户数据异常，请联系管理员！")


def show_comment_one(request, commentID):
    """
    显示一条帖子的评论
    """
    try:
        comment = models.Comment.objects.get(id=commentID)
        post = models.Post.objects.get(id=comment.post_id)
        replys = models.Reply.objects.filter(comment_id=commentID)
        return render(request, 'show_comment_one.html', {"post": post, "comment": comment, "replys": replys})
    except ForumUser.DoesNotExist:
        # 处理找不到数据的情况
        return HttpResponse("用户数据异常，请联系管理员！")
